#! /usr/bin/env python
# -*- coding: utf-8 -*-
#Author:pako
#Email:zealzpc@gmail.com
"""
One example for sina weibo search API through Basic Authorization get data

Doc:http://open.t.sina.com.cn/wiki/index.php/Statuses/search
"""
import sys
import re
import json
import time
import trendmap
import mdb
from weibopy.auth import OAuthHandler
from weibopy.api import API

debug=True
def dp(*data):
    """
    this function work the same as print()
    """
    if debug:
        if len(data)==1:
            print data
        else:
            for d in data:
                print d
    
         
def getDate():
    """
    return today's 00:00:00 unix time which format like time.time()
    """
    today=time.localtime()
    year=today.tm_year
    month=today.tm_mon
    day=today.tm_mday
    init_date_tuple=(year,month,day,0,10,10,10,0,0)
    unixTime=time.mktime(init_date_tuple)
    return unixTime

def transUinxtime2Strtime(utime,type=0):
#    stime=time.strftime("%a, %d %b",time.localtime(utime))
    if type==0:
        stime=time.strftime("%Y-%m-%d",time.localtime(utime))
        return stime
    elif type==1:
        stime=time.strftime("%m.%d",time.localtime(utime))
        return stime

pass_day_length=7#how much day's data we will to search ,default is one week


#theurl='http://api.t.sina.com.cn/statuses/search.json?source=77221908&q=asdf&needcount=10&starttime=1296028369&endtime=1298620369&filter_ori=5'

#province=
#city=
def main(pass_day_count,kw):
    """
    search keyword data 
    """
    consumer_key= '1960886904'
    consumer_secret ='a1b611395e43bbec823a76b790984bb7'
    token = 'a43a6e918eff91077ea463d832594de3'
    tokenSecret = '07146f3aa9c5105b88448879f6d37d29'
    
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.setToken(token, tokenSecret)
    api = API(auth)

    second_in_one_day=3600*24
    today_date=getDate()
    
    original_count_tread=[]
    repub_count_tread=[]
    data_list=[]
    
    interval=1 # the interval of two search date
    for i in range(0,pass_day_count,interval):
        dp("====================The result daily search data====================")
        end_time=int(today_date-i*second_in_one_day)
        i=i+interval
        start_time=int(today_date-(second_in_one_day*i))
#        dp( "time+++:",i)
        dp( "end_time:",transUinxtime2Strtime(end_time),end_time)
        dp( "start_time:",transUinxtime2Strtime(start_time),start_time)
        if (pass_day_count/interval) >10:
            data_list.append(transUinxtime2Strtime(end_time,1))
        else:
            data_list.append(transUinxtime2Strtime(end_time))
#        search_para["starttime"]=start_time
#        search_para["endtime"]=end_time
#        search_para["filter_ori"]=5
#        surl=theurl%search_para
#        search_para["filter_ori"]=0
#        dp( 'surl:',surl)
#        dp( 'rurl:',rurl)
        search_cache=mdb.daily_find(kw,end_time,interval*second_in_one_day,5)
        if search_cache:
            print 'have original cache'
            original_count_tread.append(search_cache)
        else:
            thepage = api.zpc_search(q=kw,
                                     needcount=True,
                                     count=1,
                                     starttime=start_time,
                                     endtime=end_time,
                                     filter_ori=5)
            res= json.read(thepage)
            
            total_count = res['total_count_maybe']
            result = res['results']
    #        dp( 'date:',time.strftime("%a, %d %b",time.localtime(end_time)))
    #        dp( 'original_total_count_maybe:',total_count)
            original_count_tread.append(total_count)
            mdb.daily_insert(kw,total_count,end_time,interval*second_in_one_day,5)
        
        search_cache=mdb.daily_find(kw,end_time,interval*second_in_one_day,0)
        if search_cache:
            print 'have total cache'
            repub_count_tread.append(search_cache)
        else:
            thepage = api.zpc_search(q=kw,
                                     needcount=True,
                                     count=1,
                                     starttime=start_time,
                                     endtime=end_time,
                                     filter_ori=0)
            res= json.read(thepage)
            total_count = res['total_count_maybe']
            result = res['results']
            dp('repub_total_count_maybe:',total_count)
            repub_count_tread.append(total_count)
            mdb.daily_insert(kw,total_count,end_time,interval*second_in_one_day,0)
        time.sleep(0.5)
    #    dp( 'result len:',len(result))
    #    for row in result:
    #        text=row['text']
    #        print row['id']
    #        print text
    #        print row
#        dp( "====================end====================")
    data_list.reverse()
    dp("date list:",data_list)
    original_count_tread.reverse()
    dp(  "original_count_tread:",original_count_tread,sum(original_count_tread))
    repub_count_tread.reverse()
    dp(  "repub_count_tread:",repub_count_tread,sum(repub_count_tread))
    image_data = [
                  {
                   'title':'原创微博',
#                    'title':'orignal',
                   'xAxasString':data_list,
                   'yAxasData':[str(y) for y in original_count_tread],
                   'pic_title':kw+' 在新浪微博被提及的热门趋势'
#                    'pic_title':kw
                   },
                  {
                   'title':'全部微博',
#                    'title':'all',
                   'xAxasString':data_list,
                   'yAxasData':[str(y) for y in repub_count_tread]
                   }
                  ]
    dp( "image_data:",image_data)
    return trendmap.createMap(image_data)
    
    
if __name__ == "__main__":
    print "time:",getDate()
#    dp('asdf',time.time())
    chat=main(7,'iphone4')
    print chat
#    chat=chat.decode()
#    print type(chat)
    